//
//  RootViewController.m
//  ScorePad
//
//  Created by Andy on 20/06/2010.
//  Copyright Mister Smith's Maevellous Mechanical Software Company 2010. All rights reserved.
//

#import "RootViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation RootViewController

@synthesize hands;
@synthesize playerNames;
@synthesize numberOfPlayers;


- (void)viewDidLoad {
	self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
	
	UIBarButtonItem *playersButton = [[UIBarButtonItem alloc] initWithTitle:@"Players" style:UIBarButtonItemStyleBordered target:self action:@selector(playersButtonAction)];
	
	self.navigationItem.rightBarButtonItem = playersButton;
	
	[playersButton release];


	UIBarButtonItem *newGameButton = [[UIBarButtonItem alloc] initWithTitle:@"New Game" style:UIBarButtonItemStyleBordered target:self action:@selector(newGameButtonAction)];
	
	self.navigationItem.leftBarButtonItem = newGameButton;
	
	[newGameButton release];
}


- (void)viewWillAppear:(BOOL)animated {
	
	[super viewWillAppear:animated];
	
	[self.tableView reloadData];
//	[self.tableView setNeedsLayout];
//	[self.tableView setNeedsDisplay];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/


 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
		
	return YES;
}

- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	[self.tableView reloadData];
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
}


#pragma mark Table view specific methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	int i;
	int arrayCount = [numberOfPlayers intValue];
	CGFloat magicNumber = round(tableView.frame.size.width / arrayCount);
		
	UIView* theHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, magicNumber, 22)]autorelease];
			
	for (i = 0; i < arrayCount; i++) {
		
		UILabel* theLabel = [[UILabel alloc] initWithFrame:CGRectMake(magicNumber*i, 0.0, magicNumber, 22)];
	
		theLabel.textColor = [UIColor whiteColor];
		theLabel.backgroundColor = [UIColor lightGrayColor];
		theLabel.font = [UIFont boldSystemFontOfSize:18];
		theLabel.shadowColor = [UIColor blackColor];
		theLabel.shadowOffset = CGSizeMake(0, 1.0);
		theLabel.adjustsFontSizeToFitWidth = TRUE;
		theLabel.minimumFontSize = 9;
		theLabel.lineBreakMode = UILineBreakModeMiddleTruncation;
		theLabel.textAlignment = UITextAlignmentCenter;
		theLabel.text = [playerNames objectAtIndex:i];

		[theHeaderView addSubview:theLabel];
		[theLabel release];
	}
		
	return theHeaderView;
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	return 22.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

	int i;
	int arr[] = { 0, 0, 0, 0, 0, 0, 0 };	
	
	for (NSArray *handScore in hands) {

		for (i = 0; i < [numberOfPlayers intValue]; i++) {

			arr[i] = arr[i] + [[handScore objectAtIndex:i] intValue];
		}
	}
	
	int arrayCount = [numberOfPlayers intValue];
	
	CGFloat magicNumber = round(tableView.frame.size.width / arrayCount);
	
	UIView* theFooterView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, magicNumber, 22)]autorelease];
	
	for (i = 0; i < arrayCount; i++) {
		
		UILabel* theLabel = [[UILabel alloc] initWithFrame:CGRectMake(magicNumber*i, 0.0, magicNumber, 22)];
		
		theLabel.textColor = [UIColor whiteColor];
		theLabel.backgroundColor = [UIColor lightGrayColor];
		theLabel.font = [UIFont boldSystemFontOfSize:22];
		theLabel.shadowColor = [UIColor blackColor];
		theLabel.shadowOffset = CGSizeMake(0, 1.0);
		theLabel.adjustsFontSizeToFitWidth = TRUE;
		theLabel.textAlignment = UITextAlignmentCenter;
		theLabel.text = [NSString stringWithFormat:@"%d", arr[i]];		
		[theFooterView addSubview:theLabel];
		[theLabel release];
	}	
		
	return theFooterView;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [hands count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}
	else {
		for (UIView *viewGo in cell.contentView.subviews) {
			[viewGo removeFromSuperview];
		}
		
	}
	
	if ([hands count] == indexPath.row+1) {
		
		CGFloat thisMuchAlong = cell.contentView.frame.size.width / 2;
		thisMuchAlong -= 75;
		
		UILabel* lastLabel = [[UILabel alloc] initWithFrame:CGRectMake(thisMuchAlong,10,150,25)];
		lastLabel.textAlignment = UITextAlignmentCenter;
		lastLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
		lastLabel.font = [UIFont systemFontOfSize:12];
		lastLabel.backgroundColor = [UIColor whiteColor];
		lastLabel.shadowColor = [UIColor darkGrayColor];
		lastLabel.shadowOffset = CGSizeMake(0, 1.0);
		lastLabel.layer.cornerRadius = 8;
		lastLabel.layer.borderColor = [UIColor darkGrayColor].CGColor;
		lastLabel.layer.borderWidth = 2.0;
		lastLabel.text = @"Touch to Add Score";
		
		[cell.contentView addSubview:lastLabel];
		[lastLabel release];
		
	}
	
	else {
		
		int i;
		NSArray *hand = [[NSArray alloc] initWithArray:([hands objectAtIndex:indexPath.row])];
		
		int arrayCount = [numberOfPlayers intValue];
		
		CGFloat magicNumber = round(cell.contentView.frame.size.width / arrayCount);
		
		for (i = 0; i < arrayCount; i++) {
			
			UILabel* theLabel = [[UILabel alloc] initWithFrame:CGRectMake(magicNumber*i, 0.0, magicNumber, 44)];
			theLabel.textAlignment = UITextAlignmentCenter;
			theLabel.font = [UIFont systemFontOfSize:24];
			theLabel.adjustsFontSizeToFitWidth = TRUE;
			theLabel.text = [[hand objectAtIndex:i] stringValue];
			
			[cell.contentView addSubview:theLabel];
			[theLabel release];
		}
		
		[hand release];
		
	}
	
	return cell;
	
	[cell release];
}



// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	NSUInteger numberOfHands = [hands count] - 1;
	rowSelected = indexPath.row;
		
	if (rowSelected == numberOfHands)
		weEditedLatestHand = TRUE;
	else 
		weEditedLatestHand = FALSE;
	
	// Alloc/Initialise the Edit Score View Controller
	EditScoreViewController *editScoreViewController = [[EditScoreViewController alloc] init];

	editScoreViewController.title = @"Edit Scores";
	editScoreViewController.oneHand = [hands objectAtIndex:indexPath.row];
	editScoreViewController.playerNames = self.playerNames;
	editScoreViewController.numberOfPlayers = self.numberOfPlayers;
	editScoreViewController.delegate = self;
														  
	// Push the Edit Scores View Controller onto the Navigation Controller's Stack
	[self.navigationController pushViewController:editScoreViewController animated:YES];
	
	[editScoreViewController release];
}


- (void)playersButtonAction {
	
	// Alloc/Initialise the Player Names View Controller
	PlayerNamesViewController *playerNamesViewController = [[PlayerNamesViewController alloc] init];
	
	playerNamesViewController.title = @"Players";
	playerNamesViewController.playerNames = self.playerNames;
	playerNamesViewController.numberOfPlayers = self.numberOfPlayers;
	playerNamesViewController.delegate = self;
	
	// Push the Edit Scores View Controller onto the Navigation Controller's Stack
	[self.navigationController pushViewController:playerNamesViewController animated:YES];
	
	[playerNamesViewController release];
}


- (void)newGameButtonAction {
	UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"New Game" message:@"Do you really want to end this game and start a new one?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil] autorelease];
	
	[alert addButtonWithTitle:@"Yes"];
	[alert show];
	
}


- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {

	int i;
	int handsCount = [hands count];
	
	if ((buttonIndex == 1) &&
		(handsCount > 1)) {
		
		for (i = 0; i < handsCount-1; i++) {
			
			[hands removeObjectAtIndex:0];
			
		}
	}

	[self.tableView reloadData];	
}
	

- (void)scoresDataReturned:(NSArray *)returnedArray {
	
	if (weEditedLatestHand)
		[hands insertObject:returnedArray atIndex:[hands count]-1];
	else
		[hands replaceObjectAtIndex:rowSelected withObject:returnedArray];
	
	NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsPath = [path objectAtIndex:0];
	NSString *scoresPath = [documentsPath stringByAppendingPathComponent:@"scoresArray.plist"];
	
	[hands writeToFile:scoresPath atomically:YES];
}


- (void)playersDataReturned:(NSArray *)returnedPlayers totalPlayers:(NSNumber *)playersTotal {

	[playerNames release];
	
	playerNames = returnedPlayers;
	[playerNames retain];
	
	[numberOfPlayers release];
	
	numberOfPlayers = playersTotal;
}


- (void)dealloc {
	[hands release];
	[playerNames release];
	[numberOfPlayers release];
	
	[super dealloc];
}


@end

